import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { useAppStore } from '@/stores/appStore';
import { 
  Rocket, 
  Wifi, 
  Server, 
  CheckCircle2, 
  AlertCircle, 
  Clock,
  ArrowRight,
  Globe,
  Database,
  Monitor
} from 'lucide-react';
import { OriginalDataDisplay } from '@/components/ui/OriginalDataDisplay';
import { DataFlowDrawer } from '@/components/ui/DataFlowDrawer';

interface NetworkNode {
  id: string;
  name: string;
  type: 'local' | 'gateway' | 'blockchain';
  status: 'idle' | 'processing' | 'completed' | 'error';
  position: { x: number; y: number };
  icon: React.ReactNode;
}

interface TransactionStep {
  id: string;
  name: string;
  description: string;
  status: 'pending' | 'processing' | 'completed' | 'error';
  duration: number;
  apiCall?: string;
}

export function Stage4BlockchainCall() {
  const { experienceMode, zkProofData, blockchainTx, callRecordAssetOnly } = useAppStore();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [currentStep, setCurrentStep] = useState(-1);
  const [transmissionProgress, setTransmissionProgress] = useState(0);
  const [txHash, setTxHash] = useState('');
  const [gasUsed, setGasUsed] = useState(0);
  const [apiResponse, setApiResponse] = useState<any>(null);
  const [callData, setCallData] = useState<any>(null);
  const [errorDetails, setErrorDetails] = useState<string>('');
  const [isDataFlowOpen, setIsDataFlowOpen] = useState(false);
  
  const networkNodes: NetworkNode[] = [
    {
      id: 'local',
      name: '本地客户端',
      type: 'local',
      status: 'idle',
      position: { x: 10, y: 50 },
      icon: <Globe className="w-6 h-6" />
    },
    {
      id: 'webase',
      name: '网关',
      type: 'gateway',
      status: 'idle',
      position: { x: 50, y: 30 },
      icon: <Server className="w-6 h-6" />
    },
    {
      id: 'fisco',
      name: '区块链',
      type: 'blockchain',
      status: 'idle',
      position: { x: 90, y: 50 },
      icon: <Database className="w-6 h-6" />
    }
  ];
  
  const txSteps: TransactionStep[] = [
    {
      id: 'prepare',
      name: '准备数据注册',
      description: '准备recordAsset参数：dataHash和dataDetails',
      status: 'pending',
      duration: 1000,
      apiCall: 'recordAsset(dataHash, dataDetails)'
    },
    {
      id: 'record',
      name: '注册资产数据',
      description: '调用recordAsset方法写入区块链',
      status: 'pending',
      duration: 2000,
      apiCall: 'POST /trans/handle → recordAsset'
    },
    {
      id: 'confirm',
      name: '区块链确认',
      description: '等待数据注册交易确认并获取区块高度',
      status: 'pending',
      duration: 2000,
      apiCall: 'eth_getTransactionReceipt'
    }
  ];
  
  const [nodes, setNodes] = useState(networkNodes);
  const [steps, setSteps] = useState(txSteps);
  
  useEffect(() => {
    if (experienceMode.autoplay) {
      const timer = setTimeout(() => {
        startSubmission();
      }, 2000);
      
      return () => clearTimeout(timer);
    }
  }, [experienceMode.autoplay]);
  
  // Monitor blockchainTx changes and update API response
  useEffect(() => {
    if (blockchainTx && isSubmitting) {
      setApiResponse({
        success: true,
        data: blockchainTx,
        timestamp: new Date().toISOString(),
        responseTime: Date.now() - (callData ? new Date(callData.timestamp).getTime() : Date.now())
      });
      
      if (blockchainTx.txHash) {
        setTxHash(blockchainTx.txHash);
      }
      if (blockchainTx.gasUsed) {
        setGasUsed(blockchainTx.gasUsed);
      }
    }
  }, [blockchainTx, isSubmitting, callData]);
  
  const startSubmission = async () => {
    console.log('\n=== 🚀 STAGE 4: 开始区块链调用 ===');
    console.log('步骤4.1: 检查是否已在提交中');
    
    if (isSubmitting) {
      console.log('❌ 步骤4.1失败: 区块链调用已在进行中');
      return;
    }
    
    console.log('步骤4.2: 检查证明数据是否可用');
    if (!zkProofData) {
      console.error('❌ 步骤4.2失败: 没有可用的证明数据进行区块链调用');
      console.log('=== 🚀 STAGE 4: 异常结束 ===\n');
      return;
    }
    
    console.log('✅ 步骤4.2完成: 证明数据检查通过');
    console.log('  - preImage:', zkProofData?.input?.preImage);
    console.log('  - dataHash:', zkProofData?.input?.dataHash);
    console.log('  - proof keys:', Object.keys(zkProofData?.proof || {}));
    
    console.log('\n步骤4.3: 初始化区块链调用状态');
    setIsSubmitting(true);
    setTransmissionProgress(0);
    setTxHash('');
    setGasUsed(0);
    setApiResponse(null);
    setCallData(null);
    setErrorDetails('');
    console.log('  - 提交状态: 已启动');
    console.log('  - 进度重置: 0%');
    console.log('  - 清空之前的响应数据');
    
    try {
      // Step 1: 准备交易数据
      console.log('\n--- 步骤4.4: 准备交易数据 ---');
      setCurrentStep(0);
      setSteps(prev => prev.map((step, index) => ({
        ...step,
        status: index === 0 ? 'processing' : 'pending'
      })));
      setNodes(prev => prev.map(node => 
        node.id === 'local' ? { ...node, status: 'processing' } : node
      ));
      console.log('  - 设置当前步骤: 0 (准备数据)');
      console.log('  - 更新UI状态: 本地客户端处理中');
      
      for (let progress = 0; progress <= 100; progress += 10) {
        setTransmissionProgress(progress / 3);
        await new Promise(resolve => setTimeout(resolve, 50));
        if (progress % 30 === 0) {
          console.log(`    数据准备进度: ${progress}%`);
        }
      }
      
      setSteps(prev => prev.map((step, index) => ({
        ...step,
        status: index === 0 ? 'completed' : 'pending'
      })));
      console.log('✅ 步骤4.4完成: 交易数据准备就绪');
      
      // Step 2: 发送到WeBASE网关  
      console.log('\n--- 步骤4.5: 发送到WeBASE网关 ---');
      setCurrentStep(1);
      setSteps(prev => prev.map((step, index) => ({
        ...step,
        status: index === 1 ? 'processing' : index < 1 ? 'completed' : 'pending'
      })));
      setNodes(prev => prev.map(node => ({
        ...node,
        status: node.id === 'local' ? 'completed' 
               : node.id === 'webase' ? 'processing' 
               : 'idle'
      })));
      console.log('  - 设置当前步骤: 1 (网关传输)');
      console.log('  - 更新UI状态: WeBASE网关处理中');
      
      // 记录调用数据
      console.log('\n步骤4.6: 记录调用数据');
      const requestData = {
        timestamp: new Date().toISOString(),
        method: 'recordAsset',
        preImage: zkProofData?.input?.preImage,
        dataHash: zkProofData?.input?.dataHash,
        endpoint: '/api/webase/trans/handle'
      };
      setCallData(requestData);
      console.log('  - 调用时间:', requestData.timestamp);
      console.log('  - 调用方法:', requestData.method);
      console.log('  - API端点:', requestData.endpoint);
      
      // 决定是否使用模拟调用
      const useSimulation = experienceMode.id === 'presentation' || experienceMode.id === 'quick';
      console.log('  - 使用模拟模式:', useSimulation);
      console.log('  - 体验模式:', experienceMode.id);
      
      for (let progress = 33; progress <= 66; progress += 5) {
        setTransmissionProgress(progress);
        await new Promise(resolve => setTimeout(resolve, 100));
      }
      
      // 调用区块链进行数据上链（仅recordAsset）
      console.log('\n步骤4.7: 执行数据上链操作');
      try {
        console.log('  - 开始调用callRecordAssetOnly函数...');
        console.log('  - 功能: 将dataHash和dataDetails注册到区块链');
        const success = await callRecordAssetOnly(useSimulation);
        console.log('  - 数据上链函数返回结果:', success);
        
        if (success) {
          console.log('✅ 步骤4.7完成: 数据上链成功');
          
          // Step 3: 区块链确认
          console.log('\n--- 步骤4.8: 区块链确认 ---');
          setCurrentStep(2);
          setSteps(prev => prev.map((step, index) => ({
            ...step,
            status: index === 2 ? 'processing' : index < 2 ? 'completed' : 'pending'
          })));
          setNodes(prev => prev.map(node => ({
            ...node,
            status: node.id === 'fisco' ? 'processing' 
                   : node.id === 'webase' ? 'completed'
                   : node.status
          })));
          console.log('  - 设置当前步骤: 2 (区块链确认)');
          console.log('  - 更新UI状态: FISCO区块链处理中');
          
          for (let progress = 66; progress <= 100; progress += 5) {
            setTransmissionProgress(progress);
            await new Promise(resolve => setTimeout(resolve, 80));
            if (progress % 15 === 0) {
              console.log(`    确认进度: ${progress}%`);
            }
          }
          
          // 完成所有步骤
          console.log('\n步骤4.9: 完成所有处理步骤');
          setSteps(prev => prev.map(step => ({ ...step, status: 'completed' })));
          setNodes(prev => prev.map(node => ({ ...node, status: 'completed' })));
          console.log('  - 所有步骤标记为完成');
          console.log('  - 所有网络节点标记为完成');
          
          console.log('✅ Stage4成功: 数据上链流程全部完成');
        } else {
          console.log('❌ 步骤4.7失败: 区块链调用返回失败');
          
          // 处理失败情况
          setSteps(prev => prev.map((step, index) => ({
            ...step,
            status: index === 1 ? 'error' : index < 1 ? 'completed' : 'pending'
          })));
          setNodes(prev => prev.map(node => ({
            ...node,
            status: node.id === 'webase' ? 'error' : node.status
          })));
          
          console.error('❌ Stage4失败: 区块链调用流程失败');
        }
        
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : 'Unknown error';
        console.error('❌ 步骤4.7异常: 区块链调用抛出错误:', errorMessage);
        console.error('  - 错误类型:', error instanceof Error ? error.constructor.name : typeof error);
        
        setApiResponse({
          success: false,
          error: errorMessage,
          timestamp: new Date().toISOString(),
          responseTime: Date.now() - new Date(requestData.timestamp).getTime()
        });
        
        setErrorDetails(errorMessage);
        console.log('  - 错误详情已记录到状态');
      }
      
    } catch (error) {
      console.error('❌ Stage4异常: 交易提交流程失败:', error);
      console.error('  - 错误类型:', error instanceof Error ? error.constructor.name : typeof error);
      console.error('  - 错误消息:', error instanceof Error ? error.message : String(error));
      
      setSteps(prev => prev.map((step, index) => ({
        ...step,
        status: index === currentStep ? 'error' : index < currentStep ? 'completed' : 'pending'
      })));
      console.log('  - UI状态已更新为错误状态');
    }
    
    console.log('\n步骤4.10: 清理和完成');
    setIsSubmitting(false);
    setCurrentStep(steps.length);
    console.log('  - 提交状态重置为false');
    console.log('  - 当前步骤设置为完成');
    
    console.log('=== 🚀 STAGE 4: 结束 ===\n');
  };
  
  const getNodeColor = (status: NetworkNode['status']) => {
    switch (status) {
      case 'idle': return 'text-gray-400 border-gray-600';
      case 'processing': return 'text-quantum-blue border-quantum-blue';
      case 'completed': return 'text-crypto-green border-crypto-green';
      case 'error': return 'text-red-400 border-red-400';
      default: return 'text-gray-400 border-gray-600';
    }
  };
  
  const getStepIcon = (status: TransactionStep['status']) => {
    switch (status) {
      case 'processing': 
        return (
          <motion.div
            animate={{ rotate: 360 }}
            transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
            className="w-5 h-5 border-2 border-quantum-blue border-t-transparent rounded-full"
          />
        );
      case 'completed': return <CheckCircle2 className="w-5 h-5 text-crypto-green" />;
      case 'error': return <AlertCircle className="w-5 h-5 text-red-400" />;
      default: return <Clock className="w-5 h-5 text-gray-400" />;
    }
  };
  
  return (
    <div className="stage-container">
      <div className="max-w-6xl mx-auto">
        {/* Stage title */}
        <motion.div
          initial={{ opacity: 0, y: -50 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.8 }}
          className="text-center mb-12"
        >
          <div className="flex items-center justify-between mb-6">
            <div className="flex-1"></div>
            <div className="flex-1 text-center">
              <h1 className="text-5xl font-bold gradient-text mb-4">
                🏗️ 数据上链中心
              </h1>
              <p className="text-xl text-gray-300">
                将资产数据注册到FISCO BCOS区块链（recordAsset）
              </p>
            </div>
            <div className="flex-1 flex justify-end">
              {/* 开发者模式数据流按钮 */}
              {(experienceMode.showCode || experienceMode.debugMode || experienceMode.id === 'developer') && (
                <motion.button
                  onClick={() => setIsDataFlowOpen(true)}
                  whileHover={{ scale: 1.05 }}
                  whileTap={{ scale: 0.95 }}
                  className="flex items-center space-x-2 bg-slate-800 hover:bg-slate-700 border border-slate-600 hover:border-slate-500 rounded-lg px-4 py-2 text-sm text-gray-300 hover:text-white transition-all"
                >
                  <Monitor className="w-4 h-4" />
                  <span>数据流</span>
                </motion.button>
              )}
              
              {/* 通用数据流浮动按钮 */}
              {!(experienceMode.showCode || experienceMode.debugMode || experienceMode.id === 'developer') && (
                <motion.button
                  onClick={() => setIsDataFlowOpen(true)}
                  whileHover={{ scale: 1.1 }}
                  whileTap={{ scale: 0.9 }}
                  className="bg-quantum-blue hover:bg-blue-600 text-white rounded-full p-3 shadow-lg hover:shadow-xl transition-all"
                  title="查看数据流"
                >
                  <Monitor className="w-5 h-5" />
                </motion.button>
              )}
            </div>
          </div>
        </motion.div>
        
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
          {/* Left side - Network visualization */}
          <motion.div
            initial={{ opacity: 0, x: -100 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: 0.4, duration: 0.8 }}
            className="space-y-6"
          >
            {/* Network map */}
            <div className="floating-card">
              <h3 className="text-2xl font-semibold text-white mb-6 flex items-center">
                <Wifi className="mr-3 text-quantum-blue" size={28} />
                网络拓扑图
              </h3>
              
              <div className="relative h-80 bg-slate-800 rounded-lg p-6 overflow-hidden">
                {/* Network nodes */}
                {nodes.map((node) => (
                  <motion.div
                    key={node.id}
                    className={`absolute transform -translate-x-1/2 -translate-y-1/2 w-20 h-20 rounded-full border-4 flex flex-col items-center justify-center transition-all ${getNodeColor(node.status)}`}
                    style={{
                      left: `${node.position.x}%`,
                      top: `${node.position.y}%`,
                    }}
                    animate={node.status === 'processing' ? {
                      scale: [1, 1.1, 1],
                      boxShadow: [
                        '0 0 0 rgba(59, 130, 246, 0)',
                        '0 0 20px rgba(59, 130, 246, 0.6)',
                        '0 0 0 rgba(59, 130, 246, 0)'
                      ]
                    } : node.status === 'completed' ? {
                      boxShadow: '0 0 20px rgba(16, 185, 129, 0.4)'
                    } : {}}
                    transition={{ duration: 1.5, repeat: node.status === 'processing' ? Infinity : 0 }}
                  >
                    {node.icon}
                    <span className="text-xs mt-1 text-center">{node.name.split(' ')[0]}</span>
                  </motion.div>
                ))}
                
                {/* Connection lines */}
                <svg className="absolute inset-0 w-full h-full pointer-events-none">
                  {/* Local to WeBASE */}
                  <motion.line
                    x1="10%"
                    y1="50%"
                    x2="50%"
                    y2="30%"
                    stroke={nodes[0].status === 'completed' || nodes[1].status !== 'idle' ? '#10b981' : '#64748b'}
                    strokeWidth="3"
                    strokeDasharray="10,5"
                    initial={{ pathLength: 0 }}
                    animate={{ 
                      pathLength: isSubmitting && currentStep >= 0 ? 1 : 0,
                      stroke: nodes[0].status === 'completed' || nodes[1].status !== 'idle' ? '#10b981' : '#64748b'
                    }}
                    transition={{ duration: 1 }}
                  />
                  
                  {/* WeBASE to FISCO */}
                  <motion.line
                    x1="50%"
                    y1="30%"
                    x2="90%"
                    y2="50%"
                    stroke={nodes[1].status === 'completed' || nodes[2].status !== 'idle' ? '#10b981' : '#64748b'}
                    strokeWidth="3"
                    strokeDasharray="10,5"
                    initial={{ pathLength: 0 }}
                    animate={{ 
                      pathLength: isSubmitting && currentStep >= 1 ? 1 : 0,
                      stroke: nodes[1].status === 'completed' || nodes[2].status !== 'idle' ? '#10b981' : '#64748b'
                    }}
                    transition={{ duration: 1, delay: 1 }}
                  />
                </svg>
                
                {/* Data packet animation */}
                {isSubmitting && (
                  <motion.div
                    className="absolute w-4 h-4 bg-quantum-blue rounded-full shadow-lg"
                    initial={{ left: '10%', top: '50%' }}
                    animate={{
                      left: currentStep >= 2 ? '90%' : currentStep >= 1 ? '50%' : '10%',
                      top: currentStep >= 2 ? '50%' : currentStep >= 1 ? '30%' : '50%',
                    }}
                    transition={{ duration: 1.5, ease: "easeInOut" }}
                  />
                )}
                
                {/* Progress overlay */}
                <div className="absolute bottom-4 left-4 right-4">
                  <div className="flex justify-between text-xs text-gray-300 mb-2">
                    <span>传输进度</span>
                    <span>{transmissionProgress.toFixed(0)}%</span>
                  </div>
                  <div className="w-full bg-gray-600 rounded-full h-2">
                    <motion.div
                      className="bg-gradient-to-r from-quantum-blue to-crypto-green h-2 rounded-full"
                      animate={{ width: `${transmissionProgress}%` }}
                      transition={{ duration: 0.3 }}
                    />
                  </div>
                </div>
              </div>
              
              {/* Control panel */}
              <div className="mt-6">
                <motion.button
                  onClick={startSubmission}
                  disabled={isSubmitting}
                  whileHover={{ scale: isSubmitting ? 1 : 1.02 }}
                  whileTap={{ scale: isSubmitting ? 1 : 0.98 }}
                  className={`w-full py-3 px-6 rounded-lg font-semibold transition-all ${
                    isSubmitting 
                      ? 'bg-gray-700 text-gray-500 cursor-not-allowed'
                      : 'bg-quantum-blue hover:bg-blue-600 text-white'
                  }`}
                >
                  {isSubmitting ? (
                    <span className="flex items-center justify-center">
                      <Rocket className="w-5 h-5 mr-2 animate-bounce" />
                      注册中... {transmissionProgress.toFixed(0)}%
                    </span>
                  ) : (
                    <span className="flex items-center justify-center">
                      <Rocket className="w-5 h-5 mr-2" />
                      🏗️ 注册到区块链
                    </span>
                  )}
                </motion.button>
              </div>
            </div>
            
            {/* Real-time API Data Display */}
            {(callData || apiResponse || errorDetails) && (
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                className="floating-card"
              >
                <h3 className="text-lg font-semibold text-white mb-4">🔄 实时API数据</h3>
                
                {/* Call Data */}
                {callData && (
                  <div className="mb-4">
                    <h4 className="text-sm font-medium text-gray-300 mb-2">📤 调用数据:</h4>
                    <div className="bg-slate-800 rounded p-3 text-xs">
                      <div className="space-y-1">
                        <div><span className="text-gray-400">时间:</span> <span className="text-white">{callData.timestamp}</span></div>
                        <div><span className="text-gray-400">方法:</span> <span className="text-quantum-blue">{callData.method}</span></div>
                        <div><span className="text-gray-400">preImage:</span> <span className="text-crypto-green">{callData.preImage}</span></div>
                        <div><span className="text-gray-400">dataHash:</span> <span className="text-orange-400 font-mono break-all">{callData.dataHash}</span></div>
                        <div><span className="text-gray-400">端点:</span> <span className="text-purple-400">{callData.endpoint}</span></div>
                      </div>
                    </div>
                  </div>
                )}
                
                {/* API Response */}
                {apiResponse && (
                  <div className="mb-4">
                    <h4 className="text-sm font-medium text-gray-300 mb-2">📥 API响应:</h4>
                    <div className={`bg-slate-800 rounded p-3 text-xs border-l-4 ${
                      apiResponse.success ? 'border-crypto-green' : 'border-red-400'
                    }`}>
                      <div className="space-y-1">
                        <div><span className="text-gray-400">状态:</span> 
                          <span className={`font-semibold ${
                            apiResponse.success ? 'text-crypto-green' : 'text-red-400'
                          }`}>
                            {apiResponse.success ? '✅ 成功' : '❌ 失败'}
                          </span>
                        </div>
                        <div><span className="text-gray-400">响应时间:</span> <span className="text-white">{apiResponse.timestamp}</span></div>
                        {apiResponse.responseTime && (
                          <div><span className="text-gray-400">耗时:</span> <span className="text-yellow-400">{apiResponse.responseTime}ms</span></div>
                        )}
                        {apiResponse.error && (
                          <div><span className="text-gray-400">错误:</span> <span className="text-red-400">{apiResponse.error}</span></div>
                        )}
                      </div>
                    </div>
                  </div>
                )}
                
                {/* Error Details */}
                {errorDetails && (
                  <div className="mb-4">
                    <h4 className="text-sm font-medium text-red-400 mb-2">❌ 错误详情:</h4>
                    <div className="bg-red-900/20 border border-red-400/30 rounded p-3 text-xs text-red-300">
                      {errorDetails}
                    </div>
                  </div>
                )}
                
                {/* Transaction Hash Display */}
                {txHash && (
                  <div className="mb-4">
                    <h4 className="text-sm font-medium text-gray-300 mb-2">🔗 交易哈希:</h4>
                    <div className="bg-slate-800 rounded p-3">
                      <div className="font-mono text-xs text-quantum-blue break-all">
                        {txHash}
                      </div>
                    </div>
                  </div>
                )}
                
                {/* Gas and Block Info */}
                {(gasUsed > 0 || blockchainTx?.blockNumber) && (
                  <div className="grid grid-cols-2 gap-3">
                    {gasUsed > 0 && (
                      <div className="bg-slate-800 rounded p-3 text-center">
                        <div className="text-gray-300 text-xs">Gas消耗</div>
                        <div className="text-lg font-semibold text-orange-400">{gasUsed.toLocaleString()}</div>
                      </div>
                    )}
                    
                    {blockchainTx?.blockNumber && (
                      <div className="bg-slate-800 rounded p-3 text-center">
                        <div className="text-gray-300 text-xs">区块高度</div>
                        <div className="text-lg font-semibold text-purple-400">#{blockchainTx.blockNumber}</div>
                      </div>
                    )}
                  </div>
                )}
              </motion.div>
            )}
          </motion.div>
          
          {/* Right side - Transaction steps */}
          <motion.div
            initial={{ opacity: 0, x: 100 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: 0.6, duration: 0.8 }}
            className="space-y-6"
          >
            {/* Steps list */}
            <div className="floating-card">
              <h3 className="text-2xl font-semibold text-white mb-6">📋 传输流程</h3>
              
              <div className="space-y-4">
                {steps.map((step, index) => (
                  <motion.div
                    key={step.id}
                    className={`p-4 rounded-lg border transition-all ${
                      step.status === 'processing'
                        ? 'border-quantum-blue bg-quantum-blue/10'
                        : step.status === 'completed'
                        ? 'border-crypto-green bg-crypto-green/10'
                        : step.status === 'error'
                        ? 'border-red-400 bg-red-400/10'
                        : 'border-gray-600 bg-gray-700/50'
                    }`}
                  >
                    <div className="flex items-start space-x-3">
                      <div className="mt-1">
                        {getStepIcon(step.status)}
                      </div>
                      
                      <div className="flex-1">
                        <div className="flex items-center justify-between">
                          <h4 className="font-semibold text-white">{step.name}</h4>
                          {index < steps.length - 1 && step.status === 'completed' && (
                            <ArrowRight className="w-4 h-4 text-crypto-green" />
                          )}
                        </div>
                        
                        <p className="text-gray-300 text-sm mt-1">
                          {step.description}
                        </p>
                        
                        {/* API call display for developer mode */}
                        {experienceMode.showCode && step.apiCall && (
                          <div className="mt-2 bg-slate-900 rounded p-2 text-xs font-mono text-gray-400">
                            {step.apiCall}
                          </div>
                        )}
                        
                        {/* Progress bar for current step */}
                        {step.status === 'processing' && (
                          <div className="mt-2 w-full bg-gray-600 rounded-full h-1">
                            <motion.div
                              className="bg-quantum-blue h-1 rounded-full"
                              animate={{ width: "100%" }}
                              transition={{ duration: step.duration / 1000, ease: "easeInOut" }}
                            />
                          </div>
                        )}
                      </div>
                    </div>
                  </motion.div>
                ))}
              </div>
            </div>
            
            {/* Original Data Display */}
            <OriginalDataDisplay 
              title="区块链调用数据"
              compact={true}
              showControls={experienceMode.showTechDetails || experienceMode.showCode}
              className="floating-card"
            />
            
            {/* Transaction Details */}
            {blockchainTx && currentStep >= steps.length && (
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                className="space-y-4"
              >
                {/* Success header */}
                <div className="floating-card">
                  <h3 className="text-lg font-semibold text-white mb-4 flex items-center">
                    <CheckCircle2 className="mr-2 text-crypto-green" size={20} />
                    🎉 区块链调用成功
                  </h3>
                  
                  <div className="text-center">
                    <motion.div
                      animate={{ scale: [1, 1.2, 1] }}
                      transition={{ duration: 2, repeat: 2 }}
                      className="text-6xl mb-4"
                    >
                      🚀
                    </motion.div>
                    
                    <p className="text-gray-300 mb-4">
                      零知识证明已成功提交到区块链并通过验证！
                    </p>
                  </div>
                </div>
                
                {/* Transaction Details */}
                <div className="floating-card">
                  <h4 className="text-lg font-semibold text-white mb-4">📋 交易详情</h4>
                  
                  <div className="space-y-3">
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                      <div className="bg-slate-700/50 rounded-lg p-3">
                        <div className="text-sm text-gray-400">交易哈希</div>
                        <div className="text-white font-mono text-sm break-all">
                          {txHash || blockchainTx.txHash}
                        </div>
                      </div>
                      
                      <div className="bg-slate-700/50 rounded-lg p-3">
                        <div className="text-sm text-gray-400">合约地址</div>
                        <div className="text-white font-mono text-sm break-all">
                          {blockchainTx.contractAddress}
                        </div>
                      </div>
                      
                      <div className="bg-slate-700/50 rounded-lg p-3 break-all">
                        <div className="text-sm text-gray-400">调用方法</div>
                        <div className="text-white font-mono text-sm">
                          {blockchainTx.methodName}
                        </div>
                      </div>
                      
                      <div className="bg-slate-700/50 rounded-lg p-3 break-all">
                        <div className="text-sm text-gray-400">Gas消耗</div>
                        <div className="text-white font-mono text-sm">
                          {gasUsed || blockchainTx.gasUsed || 'N/A'}
                        </div>
                      </div>
                      
                      {blockchainTx.blockNumber && (
                        <div className="bg-slate-700/50 rounded-lg p-3 break-all">
                          <div className="text-sm text-gray-400">区块高度</div>
                          <div className="text-white font-mono text-sm">
                            #{blockchainTx.blockNumber}
                          </div>
                        </div>
                      )}
                      
                      <div className="bg-slate-700/50 rounded-lg p-3">
                        <div className="text-sm text-gray-400">状态</div>
                        <div className={`text-sm font-semibold ${
                          blockchainTx.status === 'success' 
                            ? 'text-crypto-green' 
                            : blockchainTx.status === 'failed'
                            ? 'text-red-400'
                            : 'text-yellow-400'
                        }`}>
                          {blockchainTx.status === 'success' ? '✅ 验证成功' : 
                           blockchainTx.status === 'failed' ? '❌ 验证失败' : 
                           '⏳ 处理中'}
                        </div>
                      </div>
                    </div>
                    
                    {/* Detailed API Response (Developer Mode) */}
                    {experienceMode.showLogs && apiResponse && (
                      <div className="bg-slate-800 rounded-lg p-4 mt-4">
                        <div className="text-sm text-gray-400 mb-2">📊 详细API响应数据:</div>
                        <pre className="text-xs text-gray-300 overflow-x-auto max-h-64 overflow-y-auto">
                          {JSON.stringify(apiResponse, null, 2)}
                        </pre>
                      </div>
                    )}
                    
                    {/* Raw Call Data (Developer Mode) */}
                    {experienceMode.showLogs && callData && (
                      <div className="bg-slate-800 rounded-lg p-4 mt-4">
                        <div className="text-sm text-gray-400 mb-2">🚀 调用参数数据:</div>
                        <pre className="text-xs text-gray-300 overflow-x-auto">
                          {JSON.stringify(callData, null, 2)}
                        </pre>
                      </div>
                    )}
                  </div>
                </div>
                
                {/* Next Steps */}
                <div className="floating-card">
                  <motion.div
                    className="text-center text-quantum-blue"
                    animate={{ y: [0, -10, 0] }}
                    transition={{ duration: 2, repeat: Infinity }}
                  >
                    <span className="text-2xl">🏆</span>
                    <p className="font-semibold">准备进入验证阶段...</p>
                  </motion.div>
                </div>
              </motion.div>
            )}
          </motion.div>
        </div>
      </div>

      {/* Data Flow Drawer */}
      <DataFlowDrawer 
        isOpen={isDataFlowOpen} 
        onClose={() => setIsDataFlowOpen(false)} 
      />
    </div>
  );
}